using UnityEngine;
using System.Collections;

public class Player : MonoBehaviour {
	
	/// <summary>
	/// O objeto pego.
	/// </summary>
	private static GameObject objectCaught;
	public ColorFactory Factory;
	
	void Start()
	{
		Screen.lockCursor = true;
	}
	
    void Update()
	{
		Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
		RaycastHit hit;
		
		if(Input.GetKeyDown(KeyCode.Mouse0))
		{
			Screen.lockCursor = true;
			
			if(Physics.Raycast(ray,out hit,5))
			{
				if(hit.transform.gameObject.layer == 8)
				{
					if(hit.transform.gameObject.name != "rio" && hit.transform.gameObject.name != "arvore")
					{
						objectCaught = hit.transform.gameObject;
					}
					else
					{
						if(hit.transform.gameObject.name == "arvore")
						{
							objectCaught = GameObject.CreatePrimitive(PrimitiveType.Sphere);
							objectCaught.AddComponent<Rigidbody>();
							objectCaught.renderer.material.color = Color.green;
							objectCaught.tag = "Objeto";
							objectCaught.layer = 8;
						}
						
						if(hit.transform.gameObject.name == "rio")
						{
							objectCaught = GameObject.CreatePrimitive(PrimitiveType.Sphere);
							objectCaught.AddComponent<Rigidbody>();
							objectCaught.renderer.material.color = Color.blue;
							objectCaught.tag = "Objeto";
							objectCaught.layer = 8;
						}
					}
				}
				
				if(hit.transform.gameObject.layer == 9)
				{
					Factory.createCube();
					ColorPanel.DestroyComponents();
					hit.transform.audio.Play();
				}
				
				if(hit.transform.gameObject.layer == 12)
				{
					objectCaught = hit.transform.gameObject;
				}
			}
		}
		
		if(transform.position.y < -25)
		{
			transform.position = new Vector3(-3.350977f, 7.194172f, -1.342579f);
		}
		
		//se tiver pego um objeto
		if(objectCaught != null)
		{
			Vector3 mousePosition = ray.GetPoint(3);
			Quaternion rotation = objectCaught.transform.rotation;
			rotation.y = transform.rotation.y;
			
			objectCaught.rigidbody.useGravity = false;
			objectCaught.transform.rotation = rotation;
			objectCaught.transform.position = new Vector3(Mathf.Lerp(objectCaught.transform.position.x, mousePosition.x, Time.time)
			,Mathf.Lerp(objectCaught.transform.position.y, mousePosition.y, Time.time)
			,Mathf.Lerp(objectCaught.transform.position.z, mousePosition.z, Time.time));;
			
			
			if(Input.GetKeyDown(KeyCode.Mouse1))
			{
				objectCaught.rigidbody.useGravity = true;
				objectCaught.collider.isTrigger = false;
				objectCaught = null;
			}
		}
    }

	public static void ThrowAwawyCube()
	{
		objectCaught = null;
	}
	
	void OnControllerColliderHit(ControllerColliderHit other)
	{	
		if(other.gameObject.tag == "Plataforma")
		{
			if(ColorFactory.stage == 4)
			{
				ColorFactory.stage = 5;
			}
		}
		
		if(other.gameObject.tag == "Final")
		{
			Application.LoadLevel("Menu");
		}
	}
}